// word-list.js - 单词列表页面逻辑
const storageManager = require('../../../manager/storageManager.js').getInstance();

Page({
  data: {
    title: '单词列表',
    words: [], // 显示的单词列表
    allWords: [], // 存储所有单词数据
    isLoading: true,
    isLoadingMore: false,
    loadingText: '加载中...',
    sourceType: '', // 'book' 或 'category'
    sourceId: '', // 词书ID或分类名称
    totalWords: 0,
    learnedCount: 0,
    completionRate: 0, // 完成率(%)
    pageSize: 20, // 每页显示的单词数量
    currentPage: 0, // 当前页码
    hasMoreData: true, // 是否有更多数据
    currentPlayingAudio: {
      wordId: '',
      type: '' // 'uk' 或 'us'
    }
  },
  
  // 数据管理器实例 - 使用全局实例
  wordDataManager: null,
  wordLearningDataManager: null,
  
  /**
   * 页面显示时触发
   */
  onShow: function() {
    // 初始化数据管理器
    if (!this.wordDataManager) {
      const app = getApp();
      this.wordDataManager = app.globalData.wordDataManager;
    }
    if (!this.wordLearningDataManager) {
      const app = getApp();
      this.wordLearningDataManager = app.globalData.wordLearningDataManager;
    }
    
    try {
      // 检查是否有需要更新的单词信息
      const lastLearnedWordInfo = storageManager.getStorage(storageManager.STORAGE_KEYS.LAST_LEARNED_WORD_INFO);
      if (lastLearnedWordInfo && lastLearnedWordInfo.wordId) {
        // 确保当前页面的sourceType和sourceId与学习页面的一致
        if (lastLearnedWordInfo.sourceType === this.data.sourceType && 
            lastLearnedWordInfo.sourceId === this.data.sourceId) {
          // 更新单词列表中对应单词的学习次数
          this.updateWordLearnCount(lastLearnedWordInfo.wordId);
        }
      }
    } catch (error) {
      console.error('检查更新单词信息失败:', error);
    }
  },
  
  /**
   * 更新单词列表中对应单词的学习次数
   */
  updateWordLearnCount: function(wordId) {
    try {
      // 获取单词数据
      const word = this.wordDataManager.getWordById(wordId, this.data.sourceType === 'book' ? this.data.sourceId : null);
      if (!word) {
        console.error('未找到单词:', wordId);
        return;
      }
      
      // 使用WordLearningDataManager获取学习次数
      const currentLearnCount = this.wordLearningDataManager.getWordLearnCount(wordId);
      const lastLearnTime = this.wordLearningDataManager.getWordLastLearnTime(wordId);
      const isMemorized = this.wordLearningDataManager.getWordMemorizedStatus(wordId);
      
      // 查找当前单词在words数组中的索引
      const wordIndex = this.data.words.findIndex(item => item.id === wordId);
      
      if (wordIndex !== -1) {
        // 创建一个data对象用于精确更新
        const dataToUpdate = {};
        
        // 更新单词的学习相关数据
        dataToUpdate[`words[${wordIndex}].learnCount`] = currentLearnCount;
        dataToUpdate[`words[${wordIndex}].lastLearnTime`] = lastLearnTime;
        dataToUpdate[`words[${wordIndex}].memorized`] = isMemorized;
        dataToUpdate[`words[${wordIndex}].currentBookLearnCount`] = currentLearnCount;
        
        // 同时更新allWords数组中对应单词的数据
        const allWordIndex = this.data.allWords.findIndex(item => item.id === wordId);
        if (allWordIndex !== -1) {
          dataToUpdate[`allWords[${allWordIndex}].learnCount`] = currentLearnCount;
          dataToUpdate[`allWords[${allWordIndex}].lastLearnTime`] = lastLearnTime;
          dataToUpdate[`allWords[${allWordIndex}].memorized`] = isMemorized;
          dataToUpdate[`allWords[${allWordIndex}].currentBookLearnCount`] = currentLearnCount;
        }
        
        // 先更新words数组中的数据以便正确计算learnedCount
        const updatedWords = [...this.data.words];
        updatedWords[wordIndex] = {
          ...updatedWords[wordIndex],
          learnCount: currentLearnCount,
          lastLearnTime: lastLearnTime,
          memorized: isMemorized,
          currentBookLearnCount: currentLearnCount
        };
        
        // 计算更新后的已学习单词数
        const learnedCount = updatedWords.filter(wordItem => {
          if (wordItem.learningInfo && typeof wordItem.learningInfo.learnCount === 'number') {
            return wordItem.learningInfo.learnCount > 0;
          }
          return wordItem.learnCount > 0;
        }).length;
        
        const completionRate = this.data.totalWords > 0 ? Math.round((learnedCount / this.data.totalWords) * 100) : 0;
        
        // 添加已学习数量和完成率到更新数据中
        dataToUpdate.learnedCount = learnedCount;
        dataToUpdate.completionRate = completionRate;
        
        // 只更新必要的数据，避免页面重载
        this.setData(dataToUpdate);
      }
    } catch (error) {
      console.error('更新单词学习次数失败:', error);
    }
  },

  onLoad: function(options) {
    // 初始化页面数据
    const app = getApp();
    this.wordLearningDataManager = app.globalData.wordLearningDataManager;
    
    if (options.bookId) {
      this.setData({
        sourceType: 'book',
        sourceId: options.bookId
      });
      this.loadBookWords(options.bookId);
    } else if (options.category) {
      const decodedCategory = decodeURIComponent(options.category);
      this.setData({
        sourceType: 'category',
        sourceId: decodedCategory,
        title: decodedCategory
      });
      this.loadCategoryWords(decodedCategory);
    }
  },

  // 加载词书中的单词
  loadBookWords: function(bookId) {
    this.setData({ isLoading: true });
    try {
      // 确保wordDataManager已初始化
      if (!this.wordDataManager) {
        const app = getApp();
        this.wordDataManager = app.globalData.wordDataManager;
      }
      
      // 获取词书信息
      const book = this.wordDataManager.getBookById(bookId);
      if (book) {
        this.setData({ title: book.name });
      }
      
      // 获取单词列表
      const words = this.wordDataManager.getWordsByBookId(bookId);
      this.processWordsData(words);
    } catch (error) {
      console.error('加载词书单词失败:', error);
      wx.showToast({
        title: '数据加载失败',
        icon: 'none'
      });
    } finally {
      this.setData({ isLoading: false });
    }
  },

  // 加载分类中的单词
  loadCategoryWords: function(category) {
    this.setData({ isLoading: true });
    try {
      // 确保wordDataManager已初始化
      if (!this.wordDataManager) {
        const app = getApp();
        this.wordDataManager = app.globalData.wordDataManager;
      }
      
      // 获取分类中的单词
      const words = this.wordDataManager.getWordsByCategory(category);
      this.processWordsData(words);
    } catch (error) {
      console.error('加载分类单词失败:', error);
      wx.showToast({
        title: '数据加载失败',
        icon: 'none'
      });
    } finally {
      this.setData({ isLoading: false });
    }
  },

  // 处理单词数据
  processWordsData: function(words) {
    const totalWords = words.length;
    
    // 使用WordLearningDataManager计算已学习单词数量
    const learnedCount = words.filter(word => 
      this.wordLearningDataManager.getWordLearnedStatus(word.id)
    ).length;
    
    // 为每个单词添加展开状态控制和学习相关数据
    const processedWords = words.map(word => {
      // 使用WordLearningDataManager获取学习数据
      const learnCount = this.wordLearningDataManager.getWordLearnCount(word.id);
      const lastLearnTime = this.wordLearningDataManager.getWordLastLearnTime(word.id);
      const isMemorized = this.wordLearningDataManager.getWordMemorizedStatus(word.id);
      
      return {
        ...word,
        expandedSections: {
          examples: false,
          phrases: false,
          synonyms: false,
          antonyms: false
        },
        // 添加学习相关字段
        learnCount: learnCount,
        lastLearnTime: lastLearnTime,
        memorized: isMemorized,
        currentBookLearnCount: learnCount
      };
    });
    
    // 计算完成率
    const completionRate = totalWords > 0 ? Math.round((learnedCount / totalWords) * 100) : 0;
    
    this.setData({
      allWords: processedWords,
      totalWords,
      learnedCount,
      completionRate,
      currentPage: 0
    });
    
    // 加载第一页数据
    this.loadMoreWords();
  },
  
  // 加载更多单词
  loadMoreWords: function() {
    if (this.data.isLoadingMore || !this.data.hasMoreData) {
      return;
    }
    
    this.setData({ isLoadingMore: true });
    
    // 计算当前要加载的分页信息
    const { currentPage, pageSize, allWords } = this.data;
    const startIndex = currentPage * pageSize;
    const endIndex = startIndex + pageSize;
    
    // 对于词书类型，只同步当前要加载的新分页单词
    if (this.data.sourceType === 'book' && allWords.length > 0) {
      // 获取当前要加载的分页中的单词ID列表
      const wordsToLoad = allWords.slice(startIndex, endIndex);
      const wordIdsToSync = wordsToLoad.map(word => word.id);
      
      console.log(`同步第${currentPage + 1}页单词数据，共${wordIdsToSync.length}个单词`);
      
      // 使用enrichWords方法同步这一页的单词数据
      this.wordDataManager.enrichWords(wordIdsToSync, {
        onProgress: (progress) => {
          console.log(`第${currentPage + 1}页单词同步进度:`, progress);
        },
        onComplete: (results) => {
          console.log(`第${currentPage + 1}页单词同步完成，开始加载数据`);
          // 同步完成后，需要更新allWords中的数据，因为同步可能修改了单词的详细信息
          const updatedAllWords = [...allWords];
          results.forEach(syncedWord => {
            const wordIndex = updatedAllWords.findIndex(word => word.id === syncedWord.id);
            if (wordIndex !== -1) {
              // 保留原有学习状态相关字段
              updatedAllWords[wordIndex] = {
                ...updatedAllWords[wordIndex],
                ...syncedWord
              };
            }
          });
          
          // 更新allWords数据
          this.setData({ allWords: updatedAllWords });
          
          // 加载单词数据
          this._loadMoreWordsData(startIndex, endIndex);
        },
        onError: (error) => {
          console.error(`同步第${currentPage + 1}页单词数据失败:`, error);
          // 即使同步失败也继续加载单词
          this._loadMoreWordsData(startIndex, endIndex);
        }
      });
    } else {
      // 非词书类型或没有单词需要同步，直接加载
      this._loadMoreWordsData(startIndex, endIndex);
    }
  },
  
  // 实际加载更多单词数据的内部方法
  _loadMoreWordsData: function(startIndex, endIndex) {
    // 使用setTimeout模拟异步加载，避免UI阻塞
    setTimeout(() => {
      const { allWords, sourceId } = this.data;
      const newWords = allWords.slice(startIndex, endIndex);
      
      // 处理groups数据，只保留当前词书的group并提取group部分
      const processedNewWords = newWords.map(word => {
        if (word.groups && Array.isArray(word.groups)) {
          // 只保留与当前词书ID匹配的group项
          const currentBookGroups = word.groups.filter(group => {
            // 分割字符串，检查词书ID是否匹配当前词书
            const parts = group.split('-');
            return parts.length > 1 && parts[0] === sourceId;
          });
          
          // 提取group部分
          const processedGroups = currentBookGroups.map(group => {
            const parts = group.split('-');
            return parts.length > 1 ? parts[1] : group;
          });
          
          return {
            ...word,
            processedGroups
          };
        }
        return word;
      });
      
      // 将新数据追加到已有数据中
      const updatedWords = [...this.data.words, ...processedNewWords];
      const hasMoreData = endIndex < allWords.length;
      
      this.setData({
        words: updatedWords,
        currentPage: this.data.currentPage + 1,
        isLoadingMore: false,
        hasMoreData
      });
    }, 100);
  },
  
  // 监听滚动到底部事件
  onScrollToLower: function() {
    this.loadMoreWords();
  },
  
  // 切换展开/收起状态
  toggleSection: function(e) {
    const { wordId, section } = e.currentTarget.dataset;
    const words = this.data.words;
    const wordIndex = words.findIndex(word => word.id === wordId);
    
    if (wordIndex !== -1) {
      const currentState = words[wordIndex].expandedSections[section];
      const newState = !currentState;
      
      // 更新展开状态
      const key = `words[${wordIndex}].expandedSections.${section}`;
      this.setData({
        [key]: newState
      });
    }
  },

  // 切换单词学习状态
  toggleWordLearned: function(e) {
    const { wordId } = e.currentTarget.dataset;
    const { sourceType, sourceId } = this.data;
    try {
      // 确保wordDataManager已初始化
      if (!this.wordDataManager) {
        const app = getApp();
        this.wordDataManager = app.globalData.wordDataManager;
      }
      
      // 获取当前单词
      if (this.wordDataManager.getWordById(wordId)) {
        // 获取当前学习次数
        let currentLearnCount = this.wordLearningDataManager.getWordLearnCount(wordId);
        
        // 计算新的学习次数（如果当前有学习次数则重置为0，否则增加1）
        const newLearnCount = currentLearnCount > 0 ? 0 : 1;
        
        // 更新学习次数
        if (newLearnCount > 0) {
          // 如果要设置为已学习，增加学习次数
          this.wordDataManager.incrementWordLearnCount(wordId);
        } else {
          // 如果要重置为未学习，需要特殊处理
          // 注意：这里没有直接的API来重置学习次数，需要通过WordLearningDataManager来实现
            try {
              const app = getApp();
              const wordLearningDataManager = app.globalData.wordLearningDataManager;
              wordLearningDataManager.updateLearningData(wordId, {
              learnCount: 0,
              lastLearnTime: null
            });
          } catch (error) {
            console.error('重置学习次数失败:', error);
          }
        }
        
        // 更新页面数据
        const updatedWords = this.data.words.map(item => {
          if (item.id === wordId) {
            return {
              ...item,
              // 不再包含learningInfo，只保留必要的字段
              learnCount: newLearnCount,
              lastLearnTime: newLearnCount > 0 ? new Date().toISOString() : null,
              // 同步更新currentBookLearnCount字段
              currentBookLearnCount: newLearnCount
            };
          }
          return item;
        });
        
        // 同时更新allWords中的对应数据
        const updatedAllWords = this.data.allWords.map(item => {
          if (item.id === wordId) {
            return {
              ...item,
              learnCount: newLearnCount,
              lastLearnTime: this.wordLearningDataManager.getWordLastLearnTime(wordId),
              // 同步更新currentBookLearnCount字段
              currentBookLearnCount: newLearnCount
            };
          }
          return item;
        });
        
        // 使用WordLearningDataManager重新计算已学习单词数量
        const learnedCount = updatedWords.filter(wordItem => 
          this.wordLearningDataManager.getWordLearnedStatus(wordItem.id)
        ).length;
        
        // 重新计算完成率
        const completionRate = this.data.totalWords > 0 ? Math.round((learnedCount / this.data.totalWords) * 100) : 0;
        
        this.setData({
          words: updatedWords,
          allWords: updatedAllWords,
          learnedCount,
          completionRate
        });
        
        // 显示操作成功提示
        wx.showToast({
          title: newLearnCount > 0 ? '已标记为学习' : '已取消学习标记',
          icon: 'success',
          duration: 2000
        });
      } else {
        wx.showToast({
          title: '获取单词失败',
          icon: 'error',
          duration: 2000
        });
      }
    } catch (error) {
      console.error('更新单词状态失败:', error);
      wx.showToast({
        title: '操作失败，请重试',
        icon: 'error',
        duration: 2000
      });
    }
  },

  /**
   * 通知今日任务组件更新
   * 当词书激活状态变更时，调用此方法通知首页更新显示
   */
  _notifyTodayTasksToUpdate() {
    try {
      const app = getApp();
      if (app.globalData && app.globalData.todayTasksComponent) {
        // 清除缓存，确保重新获取最新数据
        app.globalData.todayTasksComponent.setData({
          cachedTaskData: null,
          cacheExpireTime: null
        });
        // 调用loadTodayTasks方法更新数据
        app.globalData.todayTasksComponent.loadTodayTasks();
      }
    } catch (e) {
      console.error('通知今日任务组件更新失败:', e);
    }
  },

  // 开始学习
  startLearning: function(e) {
    // 获取单词ID（如果有的话）
    let wordId = e && e.currentTarget && e.currentTarget.dataset ? e.currentTarget.dataset.wordId : null;
    
    // 如果没有指定单词ID，查找最后一次学习的单词
    if (!wordId) {
      wordId = this.findLastLearnedWordId();
    }
    
    if (this.data.sourceType === 'book') {
      // 设置当前词书为激活状态
      this.wordDataManager.updateBook(this.data.sourceId, { active: 1, lastActiveTime: new Date().toISOString() });
      
      // 通知首页今日任务组件更新词书显示
      this._notifyTodayTasksToUpdate();
      
      wx.navigateTo({
        url: `/pages/vocabulary/learning/learning?bookId=${this.data.sourceId}&bookName=${encodeURIComponent(this.data.title)}${wordId ? '&startWordId=' + wordId : ''}`
      });
    } else if (this.data.sourceType === 'category') {
      wx.navigateTo({
        url: `/pages/vocabulary/learning/learning?category=${encodeURIComponent(this.data.sourceId)}&categoryName=${encodeURIComponent(this.data.title)}${wordId ? '&startWordId=' + wordId : ''}`
      });
    }
  },
  
  /**
   * 查找最后一次学习的单词ID
   */
  findLastLearnedWordId: function() {
    const { words } = this.data;
    
    // 过滤出有学习记录的单词
    const learnedWords = words.filter(word => 
      this.wordLearningDataManager.getWordLearnedStatus(word.id)
    );
    
    if (learnedWords.length === 0) {
      return null;
    }
    
    // 按最后学习时间排序，返回最近学习的单词ID
    learnedWords.sort((a, b) => {
      const timeA = this.getLastLearnTime(a.id);
      const timeB = this.getLastLearnTime(b.id);
      return timeB - timeA; // 降序排列，最新的在前面
    });
    
    return learnedWords[0].id;
  },
  
  /**
   * 获取单词的最后学习时间
   */
  getLastLearnTime: function(wordId) {
    const lastLearnTime = this.wordLearningDataManager.getWordLastLearnTime(wordId);
    return lastLearnTime ? new Date(lastLearnTime).getTime() : 0;
  },
  
  // 播放音频
  playAudio: function(e) {
    const { audioUrl, type, wordId } = e.currentTarget.dataset;
    if (!audioUrl) {
      wx.showToast({
        title: '音频地址无效',
        icon: 'none'
      });
      return;
    }

    // 设置当前播放状态
    this.setData({
      currentPlayingAudio: {
        wordId: wordId,
        type: type
      }
    });

    // 创建音频上下文
    const innerAudioContext = wx.createInnerAudioContext();
    innerAudioContext.autoplay = true;
    innerAudioContext.src = audioUrl;

    innerAudioContext.onPlay(() => {
      console.log('音频播放开始');
    });

    innerAudioContext.onEnded(() => {
      console.log('音频播放结束');
      // 重置播放状态
      this.setData({
        currentPlayingAudio: {
          wordId: '',
          type: ''
        }
      });
    });

    innerAudioContext.onError((res) => {
      console.error('音频播放错误:', res);
      wx.showToast({
        title: '音频播放失败',
        icon: 'none'
      });
      // 重置播放状态
      this.setData({
        currentPlayingAudio: {
          wordId: '',
          type: ''
        }
      });
    });

    // 开始播放
    innerAudioContext.play();
  },

  // 返回上一页
  navigateBack: function() {
    wx.navigateBack();
  },
  
  /**
   * 切换单词记忆状态
   */
  toggleWordMemorized: function(e) {
    try {
      const wordId = e.currentTarget.dataset.wordId;
      const isMemorized = e.detail.value && e.detail.value.length > 0;
      
      // 调用全局WordDataManager设置单词记忆状态
      const success = this.wordDataManager.setWordMemorizedStatus(wordId, isMemorized);
      
      if (success) {
        // 更新页面数据显示
        const words = this.data.words.map(word => {
          if (word.id === wordId) {
            // 复制单词对象，避免直接修改原对象
            const updatedWord = { ...word };
            
            // 使用WordLearningDataManager更新记忆状态
            this.wordLearningDataManager.setWordMemorizedStatus(wordId, isMemorized);
            
            // 在本地数据中反映更新
            return {
              ...updatedWord,
              memorized: isMemorized
            };
          }
          return word;
        });
        
        // 同时更新allWords中的对应数据
        const allWords = this.data.allWords.map(word => {
          if (word.id === wordId) {
            const updatedWord = { ...word };
            // 使用WordLearningDataManager更新记忆状态
            this.wordLearningDataManager.setWordMemorizedStatus(wordId, isMemorized);
            
            // 在本地数据中反映更新
            return {
              ...updatedWord,
              memorized: isMemorized
            };
          }
          return word;
        });
        
        this.setData({ words, allWords });
        
        // 如果需要，可以添加Toast提示
        wx.showToast({
          title: isMemorized ? '已标记为记住' : '已取消记住',
          icon: 'none'
        });
      } else {
        wx.showToast({
          title: '设置失败，请重试',
          icon: 'none'
        });
      }
    } catch (error) {
      console.error('切换单词记忆状态失败:', error);
      wx.showToast({
        title: '操作失败，请重试',
        icon: 'none'
      });
    }
  }
});